# -*- coding: utf-8 -*-
"""
Created on Fri Oct 19 23:15:41 2018

@author: jia.liu
"""
import matplotlib.pyplot as plt
import pandas as pd
import pylab as pl

def my_boxplot(seri, y, title=''):
    pl.xticks(rotation=90)
    seri = seri.reset_index(drop=True)
    y = y.reset_index(drop=True)
    df = pd.concat([seri, y],axis=1)
    ss = seri.value_counts().sort_index()
    class_index = [i for i in ss.index]
    class_num = [j for j in ss]
    _ = list(zip(map(str,class_index),map(str,class_num)))
    x_lable = list(map(lambda x: '_'.join(x), _))
    box_data = list(map(lambda x: list(df[seri==x].SalePrice), class_index))
    #  plt.figure(figsize=(8,8))
    ax = plt.subplot()
    ax.boxplot(box_data, notch=True)
    ax.set_xticklabels(x_lable)
    ax.set_title(title)
    plt.show()

def my_boxplot_na(series, y, title=''):
    seri = series.copy()
    seri = seri.fillna('Na_temp')
    seri[seri != 'Na_temp'] = 1
    seri[seri == 'Na_temp'] = 0
    df = pd.concat([seri, y],axis=1)
    class_index = [i for i in seri.value_counts().index]
    class_num = [j for j in seri.value_counts()]
    _ = list(zip(map(str,class_index),map(str,class_num)))
    x_lable = list(map(lambda x: '_'.join(x), _))
    box_data = list(map(lambda x: list(df[seri==x].SalePrice), class_index))
    ax = plt.subplot()
    ax.boxplot(box_data, notch=True)
    ax.set_xticklabels(x_lable)
    ax.set_title(title)
    plt.show()

def my_boxplot_imbalance(df_X, y, imb_rate=0.95):
    '''
    数据分布极为不均（某种值的比例占总体比值大于imb_rate）时，也包括缺失程度巨大的，
    画出箱线图（一类为大多数值类，另一类为其它值）
    '''
    df_C = df_X.copy()
    df_C = df_C.fillna('Na_temp')
    df_C = pd.DataFrame(df_C)
    li = []
    for i in df_C.columns:
        if df_C[i].value_counts().max() > imb_rate * len(df_C[i]):
            print(df_C[i].value_counts())
            max_class = df_C[i].value_counts().argmax()
            s = df_C[i]
            print(i)
            s[s!=max_class] = 'others'
            s[s==max_class] = 'imbalance'
            my_boxplot(s,y,i)
            li.append(i)
    return li